import { useState } from "react";
import Board from "@/components/Board";

function Game() {
  // Lifting state into a parent component is common when React components are refactored.
  const [history, setHistory] = useState([Array(9).fill(null)]);
  const [currentMove, setCurrentMove] = useState(0);

  // 居然能够实时变化
  const xIsNext = currentMove % 2 === 0;
  const currentSquares = history[currentMove];

  const handlePlay = (nextSquares:Array<string>) => {
    const nextHistory = [...history.slice(0,currentMove+1), nextSquares]
    setHistory(nextHistory);
    setCurrentMove(nextHistory.length - 1)
  }

  const jumpTo = (nextMove:number) => {
    setCurrentMove(nextMove)
  }

  const movesItems = history.map((_,move)=>{

    let description = (move > 0 ? `Go to move # ${move}`: 'Go to game start')

    return (
        <li key={move}>
            <button onClick={()=>jumpTo(move)}>{description}</button>
        </li>
    )
  })
  return (
    <div className="game-container">
      <div className="game-board">
        <Board onPlay={handlePlay} squares={currentSquares} xIsNext={xIsNext}/>
      </div>

      <div className="game-info">
        <ol>{movesItems}</ol>
      </div>
    </div>
  );
}

export default Game;
